<template>
  <div class="coupon">
    <div class="header t-right">
      <el-button type="primary"
                 @click="handleAdd">新增优惠券</el-button>
    </div>
    <el-table @row-click="onChaKan"
              v-loading="loading"
              :data="couponList"
              style="width: 100%">
      <el-table-column prop="title"
                       label="优惠券标题">
      </el-table-column>
      <el-table-column label="优惠券额度">
        <template slot-scope="scope">
          <span>{{scope.row.amount | fomatMoney}}</span>
        </template>
      </el-table-column>
      <el-table-column label="满足使用金额">
        <template slot-scope="scope">
          <span>{{scope.row.amountLimit | fomatMoney }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="descs"
                       label="描述">
      </el-table-column>
      <el-table-column prop="grantCount"
                       label="优惠券数量">
      </el-table-column>
      <el-table-column prop="takeEffectTime"
                       label="有效期截至">
      </el-table-column>

      <el-table-column label="适用范围">
        <template slot-scope="scope">
          <span>{{scope.row.useType | fomatType}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作"
                       width="150">
        <template slot-scope="scope">
          <el-button size="mini"
                     plain
                     type="primary"
                     @click.stop="handleEdit(scope.$index, scope.row)">修改</el-button>
          <el-button size="mini"
                     type="danger"
                     @click.stop="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination layout="total,prev, pager, next"
                   @current-change="handleCurrentChange"
                   background
                   :total="total">
    </el-pagination>

    <!-- 修改客户基础信息 -->
    <el-dialog :title="isEdit?'编辑优惠券':'新增优惠券'"
               :before-close="onCancel"
               :close-on-click-modal="false"
               :visible.sync="dialogVisible"
               width="900px">
      <el-form :model="form"
               :rules="rules"
               ref="form"
               label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="标题"
                          prop="title">
              <el-input clearable
                        placeholder="请输入优惠券标题"
                        v-model="form.title"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="使用类型"
                          prop="useType">
              <el-select v-model="form.useType"
                         @change="useTypeChange"
                         style="width:100%"
                         placeholder="请选择">
                <el-option label="全商品"
                           :value="1"></el-option>
                <el-option label="部分商品"
                           :value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="优惠券额度"
                          prop="amount"
                          label-width="126px">
              <el-input clearable
                        v-model="form.amount"
                        suffix-icon="iconfont icon-fen"
                        placeholder="请输入优惠券额度"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="满多少使用"
                          prop="amountLimit"
                          label-width="166px">
              <el-input clearable
                        v-model="form.amountLimit"
                        suffix-icon="iconfont icon-fen"
                        placeholder="请输入优惠券满多少使用"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="产品系列"
                          prop="productId">
              <ProductInput ref="productRef"
                            :disabled="form.useType!=2"
                            :productId="form.productId"
                            @productChange="productChange" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品"
                          prop="goodsIdList">
              <GoodsInput ref="goodsRef"
                          :disabled="!form.productId"
                          :productId="form.productId"
                          :goodsIdList="form.goodsIdList"
                          @goodsChange="goodsChange" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="14">
            <el-form-item label="活动起止时间"
                          :rules="{required:true,message: '不能为空'}"
                          label-width="150">
              <el-date-picker v-model="dateTime"
                              type="daterange"
                              range-separator="至"
                              start-placeholder="开始日期"
                              end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="用户限制领取数量"
                          prop="userLimitCount"
                          label-width="150px">
              <el-input-number v-model="form.userLimitCount"
                               :min="1"
                               :max="9999"
                               label="用户限制领取数量"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="14">
            <el-form-item label="描述"
                          prop="descs">
              <el-input clearable
                        placeholder="请输入优惠券描述"
                        v-model="form.descs"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="120">
            <el-form-item label="发放数量"
                          prop="grantCount"
                          label-width="150px">
              <el-input-number v-model="form.grantCount"
                               :min="1"
                               :max="9999"
                               label="发放数量"></el-input-number>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>

      <span slot="footer"
            class="dialog-footer">
        <el-button @click="onCancel">取 消</el-button>
        <el-button type="primary"
                   @click="onSubmit('form')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getCouponList, deleteCoupon, addCoupon, updateCoupon, getCouponInfo } from '@/services/service_coupon'

import ProductInput from '../../components/common/ProductInput.vue'
import GoodsInput from '../../components/common/GoodsInput.vue'

import dayjs from 'dayjs'

const initForm = () => {
  return {
    title: '', //优惠券标题
    amount: '',//优惠券金额【分】
    amountLimit: '',//优惠券满足使用金额【分】
    descs: '',//优惠券描述
    startTime: '',//优惠券活动开始时间
    endTime: '',//优惠券活动结束时间
    goodsIdList: [],//绑定的商品id
    productId: '',//绑定的产品id
    grantCount: 1,//发放数量
    useType: '',//使用类型；1=全商品；2=部分商品
    userLimitCount: 1,//用户限制领取数量
  }
}
export default {
  name: "zixun",
  data () {
    return {
      loading: false,
      couponList: [],
      current: 1, //页码
      size: 10,//条数
      total: 0,
      // 弹窗
      dialogVisible: false,
      isEdit: false,
      dateTime: [],//活动起止时间
      form: initForm(),
      rules: {
        title: [{ required: true, message: '请输入优惠券标题', trigger: 'blur' }],
        amount: [{ required: true, message: '请输入优惠券额度【单位:分】', trigger: 'blur' }],//优惠券金额【分】
        amountLimit: [{ required: true, message: '请输入使用条件【单位:分】', trigger: 'blur' }],//优惠券满足使用金额【分】
        // dateTime: [{ required: true, message: '请选择活动起止时间', trigger: 'blur' }],//优惠券活动开始时间
        // endTime: [{ required: true, message: '请选择活动结束时间', trigger: 'blur' }],//优惠券活动结束时间
        grantCount: [{ required: true, message: '请输入发放数量', trigger: 'blur' }],//发放数量
        useType: [{ required: true, message: '请选择使用类型', trigger: 'blur' }],//使用类型；1=全商品；2=部分商品
        userLimitCount: [{ required: true, message: '请输入用户限制领取数量', trigger: 'blur' }], //用户限制领取数量
      }
    }
  },
  methods: {
    // 使用类型切换
    useTypeChange () {
      this.$set(this.form, 'goodsIdList', [])
      this.$set(this.form, 'productId', '')
    },
    // 产品切换
    productChange (val) {
      this.$set(this.form, 'goodsIdList', [])
      this.$set(this.form, 'productId', val)
    },
    // 产品切换
    goodsChange (val) {
      this.$set(this.form, 'goodsIdList', val)
    },
    onFeach () {
      this.getCouponListAll({
        current: this.current,
        size: this.size
      })
    },
    async getCouponListAll (data) {
      this.loading = true
      const res = await getCouponList(data)
      if (res.code == 0) {
        this.couponList = res.data.records
        this.total = res.data.total
        this.loading = false
      } else {
        this.$message.warning(res.msg)
        this.loading = false
      }
    },
    handleCurrentChange (val) {
      this.current = val
      this.onFeach()
    },
    // 删除
    handleDelete (index, row) {
      this.$confirm('此操作将永久删除该优惠券, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await deleteCoupon(row.id)
        if (res.code == 0) {
          this.$message.success('删除成功')
          this.onFeach()
        } else {
          this.$message.warning(res.msg)
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 修改
    async handleEdit (index, row) {
      // console.log(row);
      const res = await getCouponInfo(row.id)

      const {
        id,
        title,
        amount,
        amountLimit,
        descs,
        startTime,
        endTime,
        goodsNameList,
        goodsIdList,
        productName,
        productId,
        grantCount,
        useType,
        userLimitCount
      } = res.data

      this.dateTime = [startTime, endTime]

      // 操作prductInput和goods组件Input回显
      // console.log(this.$refs.productRef);
      this.$nextTick(() => {
        this.$refs.productRef.echo(productName)
        // this.$refs.goodsRef.echo(goodsNameList)
      })

      this.form = {
        id,
        title,
        amount,
        amountLimit,
        descs,
        startTime,
        endTime,
        grantCount,
        useType,
        userLimitCount,
        goodsIdList: goodsIdList || [],
        productId: productId || '',
      }
      this.isEdit = true
      this.dialogVisible = true
    },
    // 添加按钮
    handleAdd () {
      this.isEdit = false
      this.dialogVisible = true
    },
    // 添加，编辑
    onSubmit (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          if (this.form.useType == 2 && this.form.goodsIdList.length == 0) {
            // 如果使用类型不是全商品且产品系列，商品都为空
            return this.$message.warning('请选择优惠券绑定的商品')
          }
          if (!this.isEdit) {
            this.form.startTime = dayjs(this.dateTime[0]).format('YYYY-MM-DD HH:mm:ss')
            this.form.endTime = dayjs(this.dateTime[1]).format('YYYY-MM-DD HH:mm:ss')
            if (this.form.useType == 1) {
              delete this.form.goodsIdList
              delete this.form.productId
            }


            const res = await addCoupon(this.form)
            if (res.code == 0) {
              this.$message.success('新增成功')
              this.onCancel()
              this.onFeach()
            } else {
              this.$message.warning(res.msg)
            }
          } else {
            const res = await updateCoupon(this.form)
            if (res.code == 0) {
              this.$message.success('更新成功')
              this.onCancel()
              this.onFeach()
            } else {
              this.$message.warning(res.msg)
            }
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    onCancel () {
      this.dialogVisible = false
      this.form = initForm()
      this.dateTime = []
    },
    // 查看
    onChaKan (row) {
      console.log(row);
      this.$router.push({
        path: '/couponDetail',
        query: { id: row.id }
      })
    }
  },
  filters: {
    fomatMoney (moneyFen) {
      // console.log(moneyFen);
      return `${moneyFen / 100}元`
    },
    fomatType (type) {
      if (type == 1) {
        return '全商品'
      } else {
        return '部分商品'
      }
    }
  },
  components: {
    ProductInput,
    GoodsInput
  },
  created () {
    this.onFeach()
  }
}
</script>

<style scoped lang="scss">
.coupon {
  /* ::v-deep .el-upload-list--picture .el-upload-list__item-thumbnail {
    width: 190px;
  } */

  ::v-deep .el-table .cell {
    white-space: nowrap;
  }
}
</style>